package com.miguo.utils;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.app.FragmentActivity;
import android.webkit.WebView;
import android.widget.Toast;

import com.miguo.activity.WebViewActivity;
import com.miguo.app.AppContext;
import com.miguo.app.AppHelper;
import com.miguo.framework.app.AppFramework;
import com.miguo.framework.view.LoadingDialog;
import com.miguo.framework.view.dialogs.iface.ISimpleDialogListener;
import com.miguo.framework.web.callback.JsCallback;
import com.miguo.plugins.alibaba.BaiChuan;
import com.miguo.plugins.share.ShareQQActivity;
import com.miguo.plugins.share.ShareWXUtils;
import com.miguo.ui.R;
import com.miguo.ui.wxapi.WXEntryActivity;
import com.miguo.view.WebViewDialogFragment;
import com.miguo.view.listener.ShareListener;
import com.tencent.mm.sdk.openapi.IWXAPI;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;
import java.util.Map;


public class WebJsApi {

    private static LoadingDialog loadingDialog;

    public static String version() {
        String version = "1.0.0";
        return version;
    }

    public static int version_code() {
        int versionCode = 1;
        return versionCode;
    }

    /**
     * 文本复制功能
     */
    public static void copy(WebView webView, String text) {
        CommonUtils.copy(webView.getContext(), text);
    }

    /***** 提示相关 *****/

    /**
     * 短暂气泡提醒
     *
     * @param webView 浏览器
     * @param message 提示信息
     */
    public static void toast(WebView webView, String message) {
        Toast.makeText(webView.getContext(), message, Toast.LENGTH_SHORT).show();
    }

    /**
     * 加载框
     *
     * @param webView
     * @param json
     */
    public static void loadingDialog(WebView webView, JSONObject json) {
        loadingDialog = new LoadingDialog(webView.getContext());
        loadingDialog.setCancelable(json.optBoolean("cancelable", true));
        loadingDialog.setCanceledOnTouchOutside(json.optBoolean("canceledOnTouchOutside", false));
        loadingDialog.setMessage(json.optString("message"));
        loadingDialog.show();
    }

    public static void loadingDialogDismiss(WebView webView) {
        if (loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    public static boolean loadingDialogIsShowing(WebView webView) {
        if (loadingDialog.isShowing()) {
            return true;
        }
        return false;
    }

    /**
     * dialog
     *
     * @param webView 浏览器
     * @param json    参数 JSONObject
     */
    public static void dialog(final WebView webView, JSONObject json, final JsCallback jsCallback) {

        FragmentActivity activity = (FragmentActivity) webView.getContext();

        final String flags = json.optString("flags");

        WebViewDialogFragment.createBuilder(activity, activity.getSupportFragmentManager())
                .setCancelableOnTouchOutside(json.optBoolean("cancelable"))
                .setTitle(json.optString("title"))
                .setMessage(json.optString("message"))
                .setNeutralButtonText(json.optString("neutral"))
                .setNegativeButtonText(json.optString("negative"))
                .setPositiveButtonText(json.optString("positive"))
                .setListener(new ISimpleDialogListener() {

                    @Override
                    public void onPositiveButtonClicked(int requestCode) {
                        jsonReturn(jsCallback, 200, "确定", WebJsSign.sign(200, flags, webView.getUrl()));
                    }

                    @Override
                    public void onNegativeButtonClicked(int requestCode) {
                        jsonReturn(jsCallback, 201, "取消", WebJsSign.sign(201, flags, webView.getUrl()));
                    }

                    @Override
                    public void onNeutralButtonClicked(int requestCode) {
                        jsonReturn(jsCallback, 202, "其他", WebJsSign.sign(202, flags, webView.getUrl()));
                    }

                })
                .show();
    }

    /**
     * 系统弹出提示框
     *
     * @param webView 浏览器
     * @param message 提示信息
     */
    public static void alert(WebView webView, String message) {
        FragmentActivity activity = (FragmentActivity) webView.getContext();
        WebViewDialogFragment.createBuilder(activity, activity.getSupportFragmentManager())
                .setCancelableOnTouchOutside(true)
                .setTitle("提示")
                .setMessage(message)
                .show();
    }

    /**
     * 微信分享
     *
     * @param webView
     * @param json       scene (0:分享到微信好友，1：分享到微信朋友圈)
     * @param jsCallback
     */
    public static void shareWX(final WebView webView, JSONObject json, final JsCallback jsCallback) {

        FragmentActivity activity = (FragmentActivity) webView.getContext();

        final String flags = json.optString("flags");
        ShareListener mListener = new ShareListener() {
            @Override
            public void onComplete() {
                jsonReturn(jsCallback, 200, "分享成功", WebJsSign.sign(200, flags, webView.getUrl()));
            }

            @Override
            public void onCancel() {
                jsonReturn(jsCallback, 201, "分享取消", WebJsSign.sign(201, flags, webView.getUrl()));
            }

            @Override
            public void onError() {
                jsonReturn(jsCallback, 202, "分享错误", WebJsSign.sign(202, flags, webView.getUrl()));
            }
        };

        //注入回调接口
        WXEntryActivity.invoke(activity, mListener);
        //实例化
        IWXAPI wxApi = ShareWXUtils.register(activity);
        ShareWXUtils.disposeType(wxApi, json);
    }


    public static void shareWX(final Activity activity,JSONObject json,final ShareListener shareListener){
        //注入回调接口
        WXEntryActivity.invoke(activity, shareListener);
        //实例化
        IWXAPI wxApi = ShareWXUtils.register(activity);
        ShareWXUtils.disposeType(wxApi, json);

    }


    /*****
     * 社会化分享
     *****/
    public static void shareQQ(final WebView webView, final JSONObject json, final JsCallback jsCallback) {
        FragmentActivity activity = (FragmentActivity) webView.getContext();

        final String flags = json.optString("flags");
        ShareListener mListener = new ShareListener() {

            @Override
            public void onComplete() {
                jsonReturn(jsCallback, 200, "分享成功", WebJsSign.sign(200, flags, webView.getUrl()));
            }

            @Override
            public void onCancel() {
                jsonReturn(jsCallback, 201, "分享取消", WebJsSign.sign(201, flags, webView.getUrl()));
            }

            @Override
            public void onError() {
                jsonReturn(jsCallback, 202, "分享错误", WebJsSign.sign(202, flags, webView.getUrl()));
            }
        };
        ShareQQActivity.invoke(activity, json, mListener);
    }

    public static void shareQQ(final Activity activity,final JSONObject json, final ShareListener listener){
        ShareQQActivity.invoke(activity, json, listener);
    }

    /***** 获取信息相关 *****/

    /**
     * 获取用户登录状态
     *
     * @param webView
     * @return
     */
    public static boolean isLogin(WebView webView) {
        return AppContext.UserInfo().getIsLogin();
    }

    /**
     * 获取用户名
     *
     * @param webView
     * @return
     */
    public static String getUserName(WebView webView) {
        return AppContext.UserInfo().getUsername();
    }

    /**
     * 获取用户Token
     *
     * @param webView
     * @return
     */
    public static String getUserToken(WebView webView) {
        return AppContext.UserInfo().getToken();
    }

    /**
     * 获取系统信息
     *
     * @param webView
     * @return
     */

    public static JSONObject systemInfo(WebView webView) {
        Map<String, String> params = AppFramework.getDefaultParam();
        JSONObject json = new JSONObject();
        try {
            for (String key : params.keySet()) {
                json.put(key, params.get(key));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json;
    }


    /*****
     * 界面相关
     *****/

    /**
     * 阿里百川
     *
     * @param webView
     * @param json
     */
    public static void ailBaiChuan(WebView webView, JSONObject json) {
        if (webView.getContext() instanceof Activity) {
            Activity activity = (Activity) webView.getContext();
            if (json.optInt("type") == 1) {
                BaiChuan.showPage(activity, json.optString("title"), json.optString("url"));
            } else if (json.optInt("type") == 2) {
                BaiChuan.showTaokeItemDetailV2(activity, json.optString("title"), json.optLong("item_id"), json.optInt("item_type"));
            }
        }
    }

    /**
     * 意图启动Activity
     *
     * @param webView
     * @param json
     */
    public static void Intent(WebView webView, JSONObject json) {
        if (json.has("packageName") && json.has("className")) {
            if (webView.getContext() instanceof Activity) {
                Activity activity = (Activity) webView.getContext();
                Intent intent = new Intent();
                intent.setClassName(json.optString("packageName"), json.optString("className"));
                if (json.has("extra")) {
                    JSONObject extra = json.optJSONObject("extra");
                    Iterator it = extra.keys();
                    while (it.hasNext()) {
                        String key = (String) it.next();
                        Object value = extra.opt(key);
                        //System.out.println("key:" + key);
                        if (value instanceof String) {
                            intent.putExtra(key, extra.optString(key));
                            //System.out.println("String-value:" + extra.optString(key));
                        } else if (value instanceof Integer) {
                            intent.putExtra(key, extra.optInt(key));
                            //System.out.println("Integer-value:" + extra.optInt(key));
                        } else if (value instanceof Boolean) {
                            intent.putExtra(key, extra.optBoolean(key));
                            //System.out.println("Boolean-value:" + extra.optBoolean(key));
                        }
                    }
                }
                if (json.has("action")) {
                    //如:Intent.ACTION_VIEW = android.intent.action.VIEW
                    intent.setAction(json.optString("action"));
                }
                if (json.has("category")) {
                    //如:Intent.CATEGORY_DEFAULT = android.intent.category.DEFAULT
                    intent.addCategory(json.optString("category"));
                }
                if (json.has("data")) {
                    //如:tel:88888888
                    intent.setData(Uri.parse(json.optString("data")));
                }
                if (json.has("type")) {
                    //如:image/*
                    intent.setType(json.optString("type"));
                }
                if (json.has("flags")) {
                    //如:Intent.FLAG_ACTIVITY_NEW_TASK
                    intent.setFlags(json.optInt("flags"));
                }
                activity.startActivity(intent);
                activity.overridePendingTransition(R.anim.push_left_in, 0);
            }
        }

    }

    /**
     * 设置标题
     *
     * @param webView
     * @return String
     */
    public static void setTitle(WebView webView, String title) {
        if (webView.getContext() instanceof Activity) {
            ((WebViewActivity) webView.getContext()).jsCallbackSetTitle(title);
        }
    }

    /**
     * 显示头部
     *
     * @param webView
     */
    public static void showHeader(WebView webView) {
        if (webView.getContext() instanceof Activity) {
            ((WebViewActivity) webView.getContext()).jsCallbackShowHeader();
        }
    }

    /**
     * 隐藏头部
     *
     * @param webView
     */
    public static void hideHeader(WebView webView) {
        if (webView.getContext() instanceof Activity) {
            ((WebViewActivity) webView.getContext()).jsCallbackHideHeader();
        }
    }

    /**
     * 显示底部
     *
     * @param webView
     */
    public static void showFooter(WebView webView) {
        if (webView.getContext() instanceof Activity) {
            ((WebViewActivity) webView.getContext()).jsCallbackShowFooter();
        }
    }

    /**
     * 隐藏底部
     *
     * @param webView
     */
    public static void hideFooter(WebView webView) {
        if (webView.getContext() instanceof Activity) {
            ((WebViewActivity) webView.getContext()).jsCallbackHideFooter();
        }
    }

    /**
     * 滑屏退出设置
     *
     * @param webView
     * @param enable
     */
    public static void swipeBack(WebView webView, boolean enable) {
        if (webView.getContext() instanceof Activity) {
            ((WebViewActivity) webView.getContext()).jsCallbackSwipeBack(enable);
        }
    }

    /**
     * 设置全屏模式
     */
    public static void fullScreen(WebView webView) {
        if (webView.getContext() instanceof Activity) {
            ((WebViewActivity) webView.getContext()).jsCallbackFullScreen();
        }
    }

    /**
     * 退出全屏模式
     */
    public static void quitFullScreen(WebView webView) {
        if (webView.getContext() instanceof Activity) {
            ((WebViewActivity) webView.getContext()).jsCallbackQuitFullScreen();
        }
    }

    /**
     * 结束当前窗口
     *
     * @param webView
     */
    public static void finish(WebView webView) {
        if (webView.getContext() instanceof Activity) {
            ((Activity) webView.getContext()).finish();
        }
    }


    /***** 浏览器相关操作 *****/

    /**
     * 新窗口载入URL
     *
     * @param webView
     * @param url
     */
    public static void openUrl(WebView webView, String url) {
        if (webView.getContext() instanceof Activity) {
            Activity activity = (Activity) webView.getContext();
            AppHelper.StartWebView(activity, url);
        }
    }

    /**
     * 当前窗口载入URL
     *
     * @param webView
     */
    public static void loadUrl(WebView webView, String url) {
        webView.loadUrl(url);
    }

    /**
     * 重新载入当前页
     *
     * @param webView
     */
    public static void reload(WebView webView) {
        webView.reload();
    }

    /**
     * 获取当前页标题
     *
     * @param webView
     * @return String
     */
    public static String getTitle(WebView webView) {
        return webView.getTitle();
    }

    /**
     * 获取原始URL
     *
     * @param webView
     * @return String
     */
    public static String getOriginalUrl(WebView webView) {
        return webView.getOriginalUrl();
    }

    /**
     * 获取当前页URL
     *
     * @param webView
     * @return String
     */
    public static String getUrl(WebView webView) {
        return webView.getUrl();
    }

    /**
     * 页面前进
     *
     * @param webView
     */
    public static void goForward(WebView webView) {
        webView.goForward();
    }

    /**
     * 页面后退
     *
     * @param webView
     */
    public static void goBack(WebView webView) {
        webView.goBack();
    }

    /**
     * 页面前进或后退
     *
     * @param webView
     * @param steps
     */
    public static void goBackOrForward(WebView webView, int steps) {
        webView.goBackOrForward(steps);
    }

    /**
     * 是否可以后退
     *
     * @param webView
     * @return boolean
     */
    public static boolean canGoBack(WebView webView) {
        return webView.canGoBack();
    }

    /**
     * 是否可以前进
     *
     * @param webView
     * @return boolean
     */
    public static boolean canGoForward(WebView webView) {
        return webView.canGoForward();
    }

    /**
     * 判断是否可以跳至某页
     *
     * @param webView
     * @param steps
     * @return
     */
    public static boolean canGoBackOrForward(WebView webView, int steps) {
        return webView.canGoBackOrForward(steps);
    }


    /***** 其他 *****/

    /**
     * 其他--内部调用
     **/
    private static void jsonReturn(JsCallback jsCallback, int status, String info) {
        JSONObject result = new JSONObject();
        try {
            result.put("status", status);
            result.put("info", info);
            result.put("data", "");
            jsCallback.apply(result);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (JsCallback.JsCallbackException je) {
            je.printStackTrace();
        }
    }

    private static void jsonReturn(JsCallback jsCallback, int status, String info, String data) {
        JSONObject result = new JSONObject();
        try {
            result.put("status", status);
            result.put("info", info);
            result.put("data", data);
            jsCallback.apply(result);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (JsCallback.JsCallbackException je) {
            je.printStackTrace();
        }
    }

    private static void jsonReturn(JsCallback jsCallback, int status, String info, JSONObject data) {
        JSONObject result = new JSONObject();
        try {
            result.put("status", status);
            result.put("info", info);
            result.putOpt("data", data);
            jsCallback.apply(result);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (JsCallback.JsCallbackException je) {
            je.printStackTrace();
        }
    }

    private static void JsDataCallback(JsCallback jsCallback, Object... args) {
        try {
            jsCallback.apply(args);
        } catch (JsCallback.JsCallbackException je) {
            je.printStackTrace();
        }
    }

}
